<?php

namespace App\Eloquent\Ygt;

use Framework\BaseClass\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Engine\Func;

class Category extends DbEloquent
{
    use SoftDeletes;
    protected $table = 'ygt_category';
    protected $dates = ['deleted_at'];

    //根据type不同联合的表不同
    //默认不联合表
    public static function getJoinList($where,$limit='',$offset='',$orderby=['ygt_category.id','asc'],$type=1)
    {
        switch($type)
        {
            case 1:
                $join = [
                    ['table'=>'ygt_img_upload','field_l'=>'ygt_category.img_id','field_c'=>'=','field_r'=>'ygt_img_upload.id'],
                ];
                $column             = 'ygt_category.*';
                $column             .= ',ygt_img_upload.img_url';
                break;
            default:
                $column             = 'ygt_product.*';
                $join               = '';
        }
        $groupby            = '';
        $result             = self::getList($where,$column,$limit,$offset,$orderby,$groupby,$join);
        return $result;
    }
    //给分类填上自定义的属性
    //$lists 分类的列表,数据库中取出来的原始数据
    //$fieldsList 分类的列表中所有分类的自定义列表,数据库中取出来的原始数据
    public static function addCustomFieldsToList($lists,$fieldsList)
    {

        $fieldsListArr      = self::transformCustomFields($fieldsList);
        foreach($lists as $key=>$val)
        {
            $categoryId     = $val['id'];
            $cateFieldsArr  = [];
            if(isset($fieldsListArr[$categoryId]))
            {
                $cateFieldsArr  = $fieldsListArr[$categoryId];
            }
            $lists[$key]['cate_fields_arr'] = $cateFieldsArr;
        }
        return $lists;
    }
    //$fieldsList 分类的列表中所有分类的自定义列表,数据库中取出来的原始数据
    //返回值 格式
    // [ '分类id'=>[ [],[] ],'分类id'=>[ [],[] ] ]
    public static function transformCustomFields($fieldsList)
    {
        $result             = [];
        foreach($fieldsList as $key=>$val)
        {
            $keyId          = $val['category_id'];
            $temp           = [
                'id'=>$val['id'],
                'field_name'=>$val['field_name'],
                'unit'=>$val['field_unit'],
                'is_must'=>$val['is_must'],
                'is_compute'=>$val['is_compute'],
                'type'=>$val['type'],
            ];
            $result[$keyId][]   = $temp;
        }
        return $result;
    }

    public function getCategoryList($company_id = false)
    {
        if($company_id){
            return self::where('company_id',$company_id)->orWhere('company_id',0)->orderBy('sort_id','asc')->get();
        }else{
            return self::orderBy('sort_id','asc')->get();
        }
    }

    public function getChildrenList($pid = 0,$withP = false, $companyId)
    {
        $fields = [
            'ygt_category.*',
            'ygt_img_upload.img_url'
        ];
        if($withP){

            $CategoryList = self::where(
            function ($query) use($companyId) {
                $query->where('ygt_category.company_id', '=', $companyId)
                    ->orWhere('ygt_category.company_id', '=', 0);
            })
                ->where(function ($query) use($pid) {
                    $query->where('ygt_category.id', '=', $pid)
                          ->orWhere('pid', '=', $pid);
                })->orderBy('ygt_category.sort_id','asc')->leftJoin('ygt_img_upload','ygt_img_upload.id','=','ygt_category.img_id')->select($fields)->orderBy('sort_id','desc')->orderBy('id','asc')->get();
        }else{
            $CategoryList = self::where('pid', $pid)->where('company_id',$companyId)->orderBy('ygt_category.sort_id','asc')->leftJoin('ygt_img_upload','ygt_img_upload.id','=','ygt_category.img_id')->select($fields)->orderBy('sort_id','desc')->orderBy('id','asc')->get();
        }

        $CategoryList->transform(function ($item, $key) {
            $item['image_path'] = Func::getImgUrlHttp($item['img_url']);
            return $item;
        });
        return $CategoryList;
    }

    /**
     * @param int $pid
     * @param array $result
     * @return array 返回一维数组
     */
    public function getCategoryOption($pid = 0, $companyId, $result = [], $level = 0)
    {
        $level++;
        if($pid == 0){
            $list = self::where('pid', $pid)->where('company_id',0)->get();
        }else{
            $list = self::where('pid', $pid)->where('company_id',$companyId)->get();
        }
        $list = $list->toArray();
//        dd($list);
        foreach ($list as $k => $v) {
            $v['level'] = $level;
            $result[] = $v;
            $result = self::getCategoryOption($v['id'], $companyId, $result, $level);
        }
        return $result;
    }

    /**
     * @param int $pid
     * @param array $result
     * @return array 返回递归数组
     */
    public function getCategoryTree($pid = 0, $companyId)
    {
        $fields = [
            'ygt_category.*',
            'ygt_img_upload.img_url'
        ];
        if($pid == 0) {
            $list = self::where('pid', $pid)->where('company_id', 0)/*->orderBy('sort_id','asc')*/->leftJoin('ygt_img_upload', 'ygt_img_upload.id', '=', 'ygt_category.img_id')->select($fields)->get();
        }else{
            $list = self::where('pid', $pid)->where('company_id', $companyId)/*->orderBy('sort_id','asc')*/->leftJoin('ygt_img_upload', 'ygt_img_upload.id', '=', 'ygt_category.img_id')->select($fields)->get();
        }
//        $list = self::where('pid', $pid)->get();
        $list = $list->toArray();
//        dd($list);
        $result = [];
        foreach ($list as $k => $v) {
            $child = self::getCategoryTree($v['id'],$companyId);
            $v['child'] = $child;
            $v['image_path'] = Func::getImgUrlHttp($v['img_url']);
            $result[] = $v;
        }
        return $result;
    }

    public function addCategory($saveData)
    {
        $CategoryHandel = new self();
        return $this->saveCategory($CategoryHandel, $saveData);
    }

    public function updateCategory($updateData, $where)
    {
        $obj = self::getObject();
        $obj = $obj->setWhere($obj, $where);

        $result = $obj->update($updateData);
        return $result;
    }

    private function saveCategory(self $CategoryHandel, array $saveData)
    {
        $CategoryHandel->fill($saveData);
        return $CategoryHandel->save();
    }

    public function delCategory($CategoryId)
    {
        $CategoryHandel = self::find($CategoryId);
        if (!$CategoryHandel) xThrow(ERR_CATEGORY_NOT_EXIST);
        return $CategoryHandel->delete();
    }

    //获得分类所在层级
    public function getCategoryLvl($category_id,$lvl=0){
        if($category_id == 0){
            return $lvl;
        }
        else{
            //获得分类信息
            $info = self::where('id','=',$category_id)->first();
            if(!$info){
                return $lvl;
            }
            else{
                $category_id = $info->pid;
                $lvl++;
                return $this->getCategoryLvl($category_id,$lvl);
            }
        }

    }
}
